<template>
  <div class="app-container">
      <el-col>
        <el-card class="filter-container" shadow="never" v-if="isInArray('/system/queryPage')">
          <div>
            <i class="el-icon-search"></i>
            <span>筛选搜索</span>
            <el-button
              style="float:right"
              type="primary"
              @click="handleSearchList()"
              size="small">
              查询搜索
            </el-button>
            <el-button
              style="float:right;margin-right: 15px"
              @click="handleResetSearch()"
              size="small">
              重置
            </el-button>
          </div>
          <div style="margin-top: 15px">
            <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
              <el-form-item label="输入搜索：">
                <el-input v-model="listQuery.keyword" class="input-width" placeholder="帐号/姓名" clearable></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card class="operate-container" shadow="never">
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
          <el-button size="mini" class="btn-add" @click="handleAddAccount()" style="margin-left: 20px" v-if="isInArray('/system/register')">添加</el-button>
        </el-card>
        <el-dialog
          :title="isEdit?'编辑用户':'添加用户'"
          :visible.sync="dialogVisible"
          width="40%">
          <el-form :model="admin"
                   ref="adminForm"
                   label-width="150px" size="small">
            <el-form-item label="账户：">
              <el-input v-model="admin.staffName" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="电话：">
              <el-input v-model="admin.staffTel" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="密码：">
              <el-input v-model="admin.staffPassword"   style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item label="是否启用：">
              <el-radio-group v-model="admin.staffState">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
        </el-dialog>
        <el-dialog
          v-if="isInArray('/role/getRole/**')"
          title="分配角色"
          :visible.sync="allocDialogVisible"
          width="30%">
          <el-select v-model="allocRoleIds" multiple placeholder="请选择" size="small" style="width: 80%">
            <el-option
              v-for="item in allRoleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
        <el-button @click="allocDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAllocDialogConfirm()" size="small">确 定</el-button>
      </span>
        </el-dialog>

        <!--表格数据-->
        <div class="table-container">

          <el-table
            :data="tableData"
            highlight-current-row
            v-loading="listLoading"
            v-if="isInArray('/system/queryPage')"
            width="100"
            align="center"
            style="width: 100%">
            <el-table-column
              prop="staffId"
              label="编号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="staffName"
              label="账号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="staffTel"
              label="电话"
              width="180">
            </el-table-column>
            <el-table-column
              prop="staffCreate"
              label="创建时间" width="180">
              <template slot-scope="scope">
                {{scope.row.staffCreate | formatDateTime}}
              </template>
            </el-table-column>
            <el-table-column label="是否启用" width="140" align="center" v-if="isInArray('/system/updateState')" >
              <template slot-scope="scope">
                <el-switch
                  @change="handleStatusChange(scope.$index, scope.row)"
                  :active-value="1"
                  :inactive-value="0"
                  v-model="scope.row.staffState">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           @click="handleSelectRole(scope.$index, scope.row)"  v-if="isInArray('/role/getRole/**')">分配角色
                </el-button>
                <el-button size="mini"
                           type="text"
                           @click="handleUpdate(scope.$index, scope.row)"
                           v-if="isInArray('/system/register')"
                >
                  编辑
                </el-button>
                <el-button size="mini"
                           type="text"
                           @click="handleDelete(scope.$index, scope.row)"
                           v-if="isInArray('/system/delete/**')"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination-container" >
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="listQuery.pageNum"
                       :page-sizes="[3,5,10,20]" :page-size="listQuery.pageSize"
                       layout="total, sizes, prev, pager, next, jumper" :total="total"
                       v-if="isInArray('/system/queryPage')"
        >
        </el-pagination>
        </div>
      </el-col>
  </div>
</template>

<script>
  import {fetchList, createAdmin, updateAdmin, updateStatus, deleteAdmin, getRoleByAdmin, allocRole} from '@/api/login';
  import {fetchAllRoleList} from '@/api/role';
  import {formatDate} from '@/utils/date';
  import {setSupport,getSupport,setCookie,getCookie} from '@/utils/support';

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 3,
    keyword: null
  };

  const defaultAdmin = {
    listQuery: Object.assign({}, defaultListQuery),
    staffId: null,
    staffName: null,
    staffTel: null,
    staffPassword: null,
    staffState: 1,
    staffCreate: null,
    staffUpdate: 1,
  };

  export default {
    name: "index",
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        tableData: [],
        admin: Object.assign({}, defaultAdmin),
        total: null,
        isEdit: false,
        dialogVisible: false,
        listLoading:false,
        allRoleList:[],
        allocDialogVisible:false,
        allocRoleIds:[],
        allocAdminId:null,
        permissionList:[]
      }
    },
    created() {

      this.permissionList = eval('(' + getCookie("list") + ')')

      //得到账户列表
      this.getList();
      //得到所有角色
      this.getAllRoleList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery).then(response => {
          this.listLoading = false;
          this.tableData = response.data.list;
          this.total = response.data.total;
        });
      },
      isInArray(val){
        let array = this.permissionList;
        for(let i = 0 ; i< array.length ; i++){
          if(val ===array[i]){
            return true;
          }
        }
        return false;
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val;

        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      }, handleAddAccount() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.admin = Object.assign({}, defaultAdmin);
      },
      handleDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.isEdit) {
            updateAdmin(this.admin.staffId, this.admin).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getList();
            })
          } else {
            createAdmin(this.admin).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible = false;
              this.getList();
            })
          }
        })
      },
      handleSelectRole(index,row){
        this.allocAdminId = row.staffId;
        this.allocDialogVisible = true;
        this.getRoleListByAdmin(row.staffId);
      },
      handleUpdate(index,row){
        this.dialogVisible = true;
        this.isEdit = true;
        this.admin = Object.assign({},row);
      },
      handleDelete(index,row){
        this.$confirm('是否要删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(row.staffId)
          deleteAdmin(row.staffId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        });
      },
      handleStatusChange(index,row){
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.staffId, {status: row.staffState}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      getAllRoleList() {
        fetchAllRoleList().then(response => {
          this.allRoleList = response.data;
        });
      },
      handleAllocDialogConfirm(){
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = new URLSearchParams();
          params.append("adminId", this.allocAdminId);
          params.append("roleIds", this.allocRoleIds);

          allocRole(params).then(response => {
            this.$message({
              message: '分配成功！',
              type: 'success'
            });
            this.allocDialogVisible = false;
          })
        })
      },
      getRoleListByAdmin(adminId) {
        getRoleByAdmin(adminId).then(response => {
          let allocRoleList = response.data;
          this.allocRoleIds=[];
          if(allocRoleList!=null&&allocRoleList.length>0){
            for(let i=0;i<allocRoleList.length;i++){
              this.allocRoleIds.push(allocRoleList[i].roleId);
            }
          }
        });
      }
    }
  }
</script>

<style scoped>

</style>
